#include<bits/stdc++.h>
using namespace std;
char buf[(1<<21)+5],*p1,*p2;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
int read(){
    int f=0,x=0;
    char ch=getchar();
    while(!isdigit(ch)){f|=(ch=='-');ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
    return f?-x:x;
}
const int N=1005;
int n,m,p,c,phi,q,ans;
int a[N][N],d[N][N];
int t[10][N][N];
int power_v[10][N*N];
vector<int>s;
int power(int x,int y)
{
    int res=1;
    while(y)
    {
        if(y&1)
        {
            res=1ll*res*x%p;
        }
        x=1ll*x*x%p;
        y>>=1;
    }
    return res;
}
int main()
{
    freopen("tsuki.in","r",stdin);
    freopen("tsuki.out","w",stdout);
    n=read();
    m=read();
    c=phi=p=read();
    for(int i=2;i*i<=c;i++)
    {
        if(c%i==0)
        {
            phi=phi/i*(i-1);
            s.push_back(i);
        }
        while(c%i==0)
        {
            c/=i;
        }
    }
    if(c!=1)
    {
        phi=phi/c*(c-1);
        s.push_back(c);
    }
    for(int i=0;i<int(s.size());i++)
    {
        power_v[i][0]=1;
        for(int j=1;j<N*N;j++)
        {
            power_v[i][j]=1ll*s[i]*power_v[i][j-1]%p;
        }
    }
    for(int i=0;i<N;i++)
    {
        a[i][0]=a[0][i]=d[i][0]=d[0][i]=1;
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1,x;j<=m;j++)
        {
            x=read();
            for(int k=0;k<int(s.size());k++)
            {
                while(x%s[k]==0)
                {
                    t[k][i][j]++;
                    x/=s[k];
                }
                t[k][i][j]+=t[k][i][j-1]+t[k][i-1][j]-t[k][i-1][j-1];
            }
            a[i][j]=1ll*x*a[i][j-1]%p*a[i-1][j]%p*d[i-1][j-1]%p;
            d[i][j]=power(a[i][j],phi-1);
        }
    }
    q=read();int cnt=0;
    for(int i=1,u,v,x,y,k;i<=q;i++)
    {
        u=read()-1;
        v=read()-1;
        x=read();
        y=read();
        k=1ll*a[x][y]*d[x][v]%p*d[u][y]%p*a[u][v]%p;
        for(int j=0;j<int(s.size());j++)
        {
            if(t[j][x][y]-t[j][x][v]-t[j][u][y]+t[j][u][v]<N*N)
            {
                k=1ll*k*power_v[j][t[j][x][y]-t[j][x][v]-t[j][u][y]+t[j][u][v]]%p;
            }
            else
            {cnt++;
                k=1ll*k*power(s[j],t[j][x][y]-t[j][x][v]-t[j][u][y]+t[j][u][v])%p;
            }
        }
        ans=(ans+(k^i))%147744151;
    }
    printf("%d\n",ans);
    return 0;
}